package com.hknc.btscale;

import android.Manifest;
import android.annotation.SuppressLint;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.SystemClock;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.DialogFragment;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.arialyy.annotations.Download;
import com.arialyy.aria.core.Aria;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.hknc.btscale.adapter.DeviceItemAdapter;
import com.hknc.btscale.bean.BackToServer;
import com.hknc.btscale.bean.Constants;
import com.hknc.btscale.bean.NormalResponse;
import com.hknc.btscale.bean.TestBean1;
import com.hknc.btscale.bean.VersionApkBean;
import com.hknc.btscale.broadcast.InstallReceiver;
import com.hknc.btscale.broadcast.NetWorkStateReceiver;
import com.hknc.btscale.utils.ConnectUtils;
import com.hknc.btscale.utils.DownloadUtils;
import com.hknc.btscale.utils.NetUtils;
import com.hknc.btscale.utils.PackageUtils;
import com.hknc.btscale.utils.SPUtils;
import com.hknc.btscale.utils.SlientInstall;
import com.hknc.btscale.utils.network.ApiWrapper;
import com.hknc.btscale.utils.network.MyObserver;
import com.hknc.btscale.utils.network.RxHelper;
import com.hknc.btscale.utils.network.exception.ExceptionHandle;
import com.hknc.btscale.view.NormalDialogFragment;
import com.kongzue.dialog.util.DialogHelper;
import com.kongzue.dialog.v3.InputDialog;
import com.kongzue.dialog.v3.WaitDialog;

import org.jetbrains.annotations.NotNull;

import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.CopyOnWriteArrayList;

import cn.hutool.core.net.NetUtil;
import cn.wandersnail.bluetooth.BTManager;
import cn.wandersnail.bluetooth.ConnectCallback;
import cn.wandersnail.bluetooth.DiscoveryListener;
import io.reactivex.disposables.Disposable;
import pub.devrel.easypermissions.EasyPermissions;

public class ScanActivity extends AppCompatActivity implements EasyPermissions.PermissionCallbacks {
    private static final String TAG = "ScanActivity";
    private TextView btnSearch, versionTv, configTv;
    private CopyOnWriteArrayList<BluetoothDevice> mBluetoothDevices;
    private BluetoothDevice mBluetoothDevice;
    private RecyclerView mRecyclerView;
    private LinearLayoutManager mLinearLayoutManager;
    private DeviceItemAdapter adapter;
    private String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.INSTALL_PACKAGES, Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS};
    private boolean isFind;
    private TextView exitTv;
    private byte[] pinBytes = new byte[]{0, 0, 0, 0};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);

        new Thread(new Runnable() {
            @Override
            public void run() {
                if (!SPUtils.getInstance(getBaseContext()).getSP("base_url").equals("")) {
                    Constants.BASE_URL = SPUtils.getInstance(getBaseContext()).getSP("base_url");
                }
                if (!SPUtils.getInstance(getBaseContext()).getSP("ws_url").equals("")) {
                    Constants.WS_URL = SPUtils.getInstance(getBaseContext()).getSP("ws_url");
                }
            }
        }).start();


//        if (BTManager.getInstance().isBluetoothOn()) {
//            Toast.makeText(getBaseContext(), "开启！！", Toast.LENGTH_SHORT).show();
//            Log.e(TAG, "嘎嘎阿嘎嘎: " + "开启");
//        } else {
//            Toast.makeText(this, "关闭", Toast.LENGTH_SHORT).show();
//            Log.e(TAG, "嘎嘎阿嘎嘎: " + "关闭");
//            Intent intent = new Intent(ScanActivity.this, LoginActivity.class);
//            intent.putExtra("device", SPUtils.getInstance(getApplicationContext()).getSP("device"));
//            startActivity(intent);
//            finish();
//        }

//        if (!NetUtils.ping()) {
//            startActivity(new Intent(ScanActivity.this, YangcanliActivity.class));
//            finish();
//        }
//        Constants.BASE_URL = SPUtils.getInstance(ScanActivity.this).getSP("base_url");
//        Constants.WS_URL = SPUtils.getInstance(ScanActivity.this).getSP("ws_url");
        mLinearLayoutManager = new LinearLayoutManager(this);
        mBluetoothDevices = new CopyOnWriteArrayList<>();

        initView();

        initAdapter();
        initListener();
        EasyPermissions.requestPermissions(this, "权限请求", 1, perms);

//        && NetUtils.ping()
        if (!TextUtils.isEmpty(SPUtils.getInstance(getBaseContext()).getSP("marketId"))) {
            versionCheck();
        } else {
            BTManager.getInstance().startDiscovery();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        // Forward results to EasyPermissions
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> list) {

    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> list) {
        // Some permissions have been denied
        // ...
    }

    private DiscoveryListener discoveryListener = new DiscoveryListener() {
        @Override
        public void onDiscoveryStart() {
            //搜索开始
            Log.e(TAG, "onDiscoveryStart: ");
        }

        @Override
        public void onDiscoveryStop() {
            Log.e(TAG, "onDiscoveryStop: ");
            if (!isFind) {
                mBluetoothDevices.clear();
                BTManager.getInstance().startDiscovery();
            }

            //搜索停止
        }

        /**
         * 搜索到蓝牙设备
         *
         * @param device 搜索到的设备
         * @param rssi   信号强度
         */
        @Override
        public void onDeviceFound(@NonNull BluetoothDevice device, int rssi) {
            if (device.getAddress().equals(SPUtils.getInstance(getApplicationContext()).getSP("device"))) {
                isFind = true;
                BTManager.getInstance().stopDiscovery();
//                if (device.setPin(pinBytes)) {
                BTManager.getInstance().createConnection(device.getAddress())
                        .connect(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"),
                                new ConnectCallback() {
                                    @Override
                                    public void onSuccess() {
                                        Log.e(TAG, "createConnection+成功");
                                        SPUtils.getInstance(getApplicationContext()).putSP("device", device.getAddress());
                                        BaseApplication.sDevice = device;
                                        WaitDialog.dismiss();

                                        Intent intent = new Intent(ScanActivity.this, LoginActivity.class);
                                        intent.putExtra("device", device);
                                        startActivity(intent);
                                        finish();
                                    }

                                    @Override
                                    public void onFail(@NonNull String errMsg, @Nullable Throwable e) {
                                        Log.e(TAG, "onFail: ");
                                        Log.e(TAG, "createConnection+失败");

                                        WaitDialog.dismiss();

                                        runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                Toast.makeText(getApplicationContext(), "连接失败：" + errMsg, Toast.LENGTH_SHORT).show();
//                                    BTManager.getInstance().releaseAllConnections();
//                                    BTManager.getInstance().disconnectAllConnections();
//                                    BTManager.getInstance().destroy();
                                                new Handler().postDelayed(new Runnable() {
                                                    @Override
                                                    public void run() {
                                                        Intent LaunchIntent = getPackageManager().getLaunchIntentForPackage(getApplication().getPackageName());
                                                        LaunchIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                                                        startActivity(LaunchIntent);
                                                    }
                                                }, 1000);// 1秒钟后重启应用
                                            }
                                        });
                                    }
                                });
//                } else {
//                    new Handler().postDelayed(new Runnable() {
//                        @Override
//                        public void run() {
//                            Intent LaunchIntent = getPackageManager().getLaunchIntentForPackage(getApplication().getPackageName());
//                            LaunchIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//                            startActivity(LaunchIntent);
//                        }
//                    }, 1000);// 1秒钟后重启应用
//                }
            }
            //搜索结果
            mBluetoothDevices.add(device);
            adapter.notifyDataSetChanged();
        }

        @Override
        public void onDiscoveryError(int errorCode, @NotNull String errorMsg) {
            Log.e(TAG, "onDiscoveryError: " + errorMsg);
        }
    };


    /**
     * 初始化搜索到的设备列表
     */
    private void initAdapter() {
        adapter = new DeviceItemAdapter(mBluetoothDevices, this, R.layout.item_device);
        mRecyclerView.setLayoutManager(mLinearLayoutManager);
        mRecyclerView.setAdapter(adapter);
        mRecyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
    }

    private void initView() {
        btnSearch = findViewById(R.id.btn_search);
        versionTv = findViewById(R.id.version_tv);
        configTv = findViewById(R.id.config_tv);
        mRecyclerView = findViewById(R.id.recycler_view);
        exitTv = findViewById(R.id.exit_btn);

        versionTv.setText("版本号：" + PackageUtils.getLocalVersionName(getApplicationContext()) + "");
    }

    /**
     * 初始化监听
     */
    private void initListener() {
        exitTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                System.exit(0);
            }
        });
        BTManager.getInstance().addDiscoveryListener(discoveryListener);

        versionTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });

        configTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isFind = true;
                BTManager.getInstance().stopDiscovery();
                NormalDialogFragment normalDialogFragment = new NormalDialogFragment();
                normalDialogFragment.show(getSupportFragmentManager(), "aa");
                normalDialogFragment.setCommitCallBack(new NormalDialogFragment.CommitCallBack() {
                    @Override
                    public void commit(String baseUrl, String wsUrl) {
                        normalDialogFragment.dismiss();
                        SPUtils.getInstance(getBaseContext()).putSP("base_url", baseUrl);
                        SPUtils.getInstance(getBaseContext()).putSP("ws_url", wsUrl);
                        Constants.BASE_URL = baseUrl;
                        Constants.WS_URL = wsUrl;
                    }
                });
            }
        });

        //搜索按钮监听
        btnSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.e(TAG, "onClick: ");
                scanBt();
            }
        });

        //点击条目监听
        adapter.setOnItemClickListener(new DeviceItemAdapter.OnItemClickListener() {
            @SuppressLint("CheckResult")
            @Override
            public void onClick(int position) {
                isFind = true;
                BTManager.getInstance().stopDiscovery();
                WaitDialog.showWait(ScanActivity.this, "连接中...");
                mBluetoothDevice = mBluetoothDevices.get(position);
//                if (mBluetoothDevice.setPin(pinBytes)) {
                BTManager.getInstance().createConnection(mBluetoothDevice.getAddress()).connect(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"), new ConnectCallback() {
                    @Override
                    public void onSuccess() {
                        SPUtils.getInstance(getApplicationContext()).putSP("device", mBluetoothDevice.getAddress());
                        Log.e(TAG, "onSuccess: " + "连接成功" + Thread.currentThread().getName());
                        BaseApplication.sDevice = mBluetoothDevice;
                        WaitDialog.dismiss();
                        Intent intent = new Intent(ScanActivity.this, LoginActivity.class);
                        intent.putExtra("device", mBluetoothDevice);
                        startActivity(intent);
                        finish();
                    }

                    @Override
                    public void onFail(@NonNull String errMsg, @Nullable Throwable e) {
                        Log.e(TAG, "onFail: ");
                        WaitDialog.dismiss();
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(getApplicationContext(), "连接失败：" + errMsg, Toast.LENGTH_SHORT).show();
                            }
                        });
                    }
                });
            }
//            }
        });

    }

    /**
     * 初始化蓝牙//扫描蓝牙
     */
    private void scanBt() {
        BTManager.getInstance().stopDiscovery();
        mBluetoothDevices.clear();
        BTManager.getInstance().startDiscovery();
    }

    private void versionCheck() {
        Log.e(TAG, "versionCheck: ");
        ApiWrapper.getInstance().apkVersion(SPUtils.getInstance(getBaseContext()).getSP("marketId"))
                .compose(RxHelper.to_mian())
                .subscribe(new MyObserver<VersionApkBean>() {
                    @Override
                    public void onError(ExceptionHandle.ResponseException responseException) {

                    }

                    @Override
                    public void onSubscribe(@io.reactivex.annotations.NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@io.reactivex.annotations.NonNull VersionApkBean versionApkBean) {
//                        BTManager.getInstance().startDiscovery();
                        if (versionApkBean.getCode() == 200 && versionApkBean.getData() != null) {
                            if (!PackageUtils.getLocalVersionName(getApplicationContext()).equals(versionApkBean.getData().getVersion())) {
                                WaitDialog.showWait(ScanActivity.this, "更新app中，请稍后..");
                                versionNew = versionApkBean.getData().getVersion();
                                downloadUrl = versionApkBean.getData().getDownloadUrl();
                                downloadApk(versionApkBean.getData().getDownloadUrl());
                            } else {
                                BTManager.getInstance().startDiscovery();
                            }
                        } else {
                            BTManager.getInstance().startDiscovery();
                        }

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private String versionNew;
    private String downloadUrl;

    private void downloadApk(String downloadUrl) {
        try {
            DownloadUtils.downloadFile(ScanActivity.this, Environment.getExternalStorageDirectory().getAbsolutePath(),
                    "/yangcanli.apk", downloadUrl, new DownloadUtils.DownLoadListener() {
                        @Override
                        public void onDownloading(int progress) {
                            Log.e(TAG, "onDownloading: " + progress);
                        }

                        @Override
                        public void onDownloadSuccess() {
                            Log.e(TAG, "onDownloadSuccess: ");
                            SlientInstall.install(Environment.getExternalStorageDirectory().getAbsolutePath() + "/yangcanli.apk");
                        }

                        @Override
                        public void onDownloadFailed() {
                            WaitDialog.dismiss();
                            BTManager.getInstance().startDiscovery();
                            Log.e(TAG, "onDownloadFailed: ");
                            BackToServer backToServer = new BackToServer();
                            backToServer.setType(5);//1:下发商品、2：小票信息、3：开秤锁称、4:下发校时5:下发更新apk
                            backToServer.setMarketId(SPUtils.getInstance(getApplicationContext()).getSP("marketId"));
                            backToServer.setPlu("");
                            backToServer.setStallId(SPUtils.getInstance(getApplicationContext()).getSP("stallId"));
                            backToServer.setStatusCode(200);
                            backToServer.setStatusMsg(versionNew);
                            ApiWrapper.getInstance().backToServer(backToServer)
                                    .compose(RxHelper.to_mian())
                                    .subscribe(new MyObserver<NormalResponse>() {
                                        @Override
                                        public void onError(ExceptionHandle.ResponseException responseException) {

                                        }

                                        @Override
                                        public void onSubscribe(@io.reactivex.annotations.NonNull Disposable d) {

                                        }

                                        @Override
                                        public void onNext(@io.reactivex.annotations.NonNull NormalResponse normalResponse) {

                                        }

                                        @Override
                                        public void onComplete() {

                                        }
                                    });

                        }
                    });
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }

}